<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <div class="grid-content bg-purple">
          <el-card>
            <el-container>
              <el-aside width="33%">
                <img src="../assets/imgs/linux.png" style="width: 100%;">
              </el-aside>
              <el-main>
                <div class="event">
                  <span class="event-title">感知主机节点数量</span><br><br>
                  <span class="event-nums">{{eventNums}}</span>
                </div>
              </el-main>
            </el-container>
          </el-card>
          <!--分数最低的五个ip-->
          <el-card style="margin-top: 10px">
            <div>
              <span style="font-weight: bold; color: #4b4b4b; font-size: 18px">危险Top5</span><br><br>
            </div>
            <el-table :data="filData">
              <!--显示序号，ip,分数，安全事件-->
              <el-table-column type="index"></el-table-column>
              <el-table-column min-width="45%" prop="ip" label="IP"></el-table-column>
              <el-table-column min-width="30%" label="安全事件">
                <template v-slot="scope">
                  <el-button @click="viewDetails(scope.row.securityEvent)" type="text" size="mini">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
      </div>
      </el-col>
      <!--折线图-->
      <el-col :span="18">
        <div class="grid-content bg-purple-light">
          <el-card id="main" :style="{width: '100%', height: height + 'px'}"></el-card>
      </div>
      </el-col>
    </el-row>
    <!--详情对话框-->
    <el-dialog title="安全事件详情" :visible.sync="centerDialogVisible" width="50%">
      <ul>
        <li  v-for="(item,index) in details" :key="item.id" >
          <p>{{details[index]}}</p>
        </li>
      </ul>
      <!--<span class="detail" v-html="details"></span>-->
    </el-dialog>
    <!-- 全屏弹框 -->
    <!--<el-dialog title="全屏显示" :visible.sync="dialogVisible" :fullscreen="true" center>
      <div id="main1" ref="fullChart" :style="'width:100%;height:' + (screenHeight - 110) + 'px'" />
    </el-dialog>-->
  </div>
</template>

<script>
export default {
  created() {
    this.getData();
    // 填充图表
    /*this.fillData();
    this.filterData();*/
  },
  mounted() {
    // 自适应浏览器大小
    this.autoScreen();

    // 获取浏览器窗口大小（全屏）
    /*window.onresize = () => {
      return (() => {
        window.screenHeight = window.innerHeight
        this.screenHeight = window.screenHeight
      })()
    }*/
  },
  //移除事件监听
  beforeDestroy() {
    window.removeEventListener('resize', this.myChart);
  },
  data() {
    return {
      myChart:{},
      dialogVisible: false,
      screenHeight: window.innerHeight,
      // 当前电脑屏幕的60%
      height: window.screen.availHeight * 0.66,
      // 保存最初全部的数据
      tableData: [],
      // 保存展示的数据
      filData: [],
      centerDialogVisible: false,
      details: [],
      eventNums: '',
      xData: [],
      series: []
    }
  },
  methods: {
    // 获取总数据
    getData() {
      this.$axios.get('/awareness/event/select_in_seven_day')
        .then((res)=> {
          // console.log(res);
          this.tableData = res.data.result.data;
          this.eventNums = res.data.result.data.length;
          // 填充图表
          this.fillData();
          this.filterData()
          // 筛选数据
          // this.filterData();
        })
        .catch(() => {
          // this.$message.error('获取数据失败！');
        });
    },
    // 填充数据
    fillData() {
      // 从后端拿到的数据
      this.$axios.get('/awareness/event/select_every_day')
        .then((res)=> {
          // console.log(res);

          // 获取当前日期
          var currentDate = new Date();

          var backendData = [];
          if (res.data.result.data != null) {
            // ip数组
            var ips = Object.keys(res.data.result.data);
            for (var i = 0; i < ips.length; i++) {
              // 根据key获取value
              var scoreObj = res.data.result.data[ips[i]];
              var score = [];
              var dateKey = Object.keys(scoreObj);
              // 按日期筛选value
              for (var j = 0; j < 7; j++) {
                var time = this.$moment(currentDate - j*24*60*60*1000).format("YYYY-MM-DD");
                // console.log(time);
                // 如果当前value对象的 时间key 包含当前的日期，则在当前位置赋值其value，否则赋值空串''
                if (dateKey.indexOf(time) != -1) {
                  var scoreValue = scoreObj[time];
                  score[j] = scoreValue;
                } else {
                  score[j] = '';
                }
              }
              // 逆序数组
              var temp;
              for (let i = 0; i < score.length / 2; i++) {
                temp = score[i];
                score[i] = score[score.length-1-i];
                score[score.length-1-i] = temp;
              }
              // console.log(score);
              // 将数据放入数组
              var obj = {};
              obj.ip = ips[i];
              obj.score = score;
              backendData.push(obj);
            }
            // 设置数据
            for (var i=0; i< backendData.length; i++) {
              var obj = {};
              obj.type = 'line';
              obj.name = backendData[i].ip;
              obj.data = backendData[i].score;
              this.series.push(obj);
            }
          }
          // 设置x轴日期
          for (var i = 0; i < 7; i++) {
            var date = this.$moment(currentDate - i*24*60*60*1000).format('YYYY/MM/DD');
            // 每次从前面插入数据
            this.xData.unshift(date);
          }
          //初始化echarts
          this.echartsInit();
          // console.log("初始化成功");
        })
        .catch(() => {
          // this.$message.error('获取数据失败！');
        });
    },
    // 查看详情
    viewDetails(info) {
      this.centerDialogVisible = true;
      this.details = info.split('||');
    },
    // 筛选出分数最低的五个数据
    filterData() {
      // 因为sort方法会改变原数组，所以备份一下
      var arr = [];
      for (var i = 0; i < this.tableData.length; i++) {
        arr.push(this.tableData[i]);
      }
      arr.sort((a, b) => {
        return a.score - b.score;
      });
      // 此时arr已经按照分数升序排好了
      if (arr.length <= 5) {
        this.filData = arr;
      } else {
        // 只拿前五个
        for (let i = 0; i < 5; i++) {
          this.filData.unshift(arr[i]);
        }
      }
    },
    //初始化echarts
    echartsInit() {
      //初始化echarts指定的容器 id='main'
      this.myChart = this.$echarts.init(document.getElementById('main'));
      this.myChart.setOption({
        title: {
          text: '近七天分数走势图',
          x: 'center',
          padding: 15
        },
        // 鼠标悬停显示当前折现信息
        tooltip: {
          trigger: 'axis'
        },
        // 图例
        /*legend: {
          data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
        },*/
        // 控制位置
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        // 保存为图片按钮
        toolbox: {
          feature: {
            saveAsImage: {},
            /*myFull: { // 全屏
              show: true,
              title: '全屏',
              icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
              onclick: () => {
                // 全屏查看
                this.dialogVisible = true// 打开弹窗
                this.$nextTick(() => {
                  const chartFul = this.$refs.fullChart
                  if (chartFul) {
                    this.echartsInitFull();// 画图
                  }
                })
              }
            }*/
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          // x轴数据
          data: this.xData
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          interval: 10
        },
        // 线段数据
        series: this.series
      });
    },
    //全屏图表
    /*echartsInitFull() {
      //初始化echarts指定的容器 id='main'
      this.$echarts.init(document.getElementById('main1')).setOption({
        title: {
          text: '近七天分数走势图',
          x: 'center',
          padding: 15
        },
        // 鼠标悬停显示当前折现信息
        tooltip: {
          trigger: 'axis'
        },
        // 图例
        /!*legend: {
          data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
        },*!/
        // 控制位置
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        // 保存为图片按钮
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          // x轴数据
          data: this.xData
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          interval: 10
        },
        // 线段数据
        series: this.series
      });
    },*/
    // 自适应浏览器大小
    autoScreen() {
      let _this = this;
      let that = this;
      window.addEventListener("resize",function (){
        _this.myChart.resize();
      })
      // 随外层el-card大小自适应
      this.$erd.listenTo(this.$refs.agriEcoDev, (element) => {
        that.$nextTick(() => {
          _this.myChart.resize();
        })
      })
    }
  },
  // 监听screenHeight大小，从而改变全屏画图容器的大小
  /*watch: {
    screenHeight(val) {
      this.screenHeight = val;
    }
  },*/
}
</script>

<style scoped>
.el-main {
  padding: 0;
}
.event {
  float: right;
  text-align: center
}
.event-title {
  /*font-size: 14px;*/
  font-weight: bold;
  color: red;
}
.event-nums {
  font-weight: bold;
  font-size: 20px;
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  line-height: 25px;
}
/deep/ .el-dialog__header {
  background-color: #87b6da;
  padding: 10px;
}
/deep/ .el-dialog__title {
  color: white;
  font-family: 黑体;
}
</style>